package com.zHan.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zHan.sky.common.contant.MessageConstant;
import com.zHan.sky.common.exception.LoginFailedException;
import com.zHan.sky.common.properties.WeChatProperties;
import com.zHan.sky.common.utils.HttpClientUtil;
import com.zHan.sky.dto.UserLoginDTO;
import com.zHan.sky.entity.User;
import com.zHan.sky.mapper.UserMapper;
import com.zHan.sky.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    public static final String VX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private WeChatProperties weChatProperties;

    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {
        // 调用微信接口服务，获得用户的openId
        String openid = getOpenid(userLoginDTO);

        // 如果openid为空，说明登录失败，抛出异常
        if (!StringUtils.hasText(openid)) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        // 判断用户是否为新用户
        User user = lambdaQuery().eq(User::getOpenid, openid).one();
        if (user == null) {
            // 如果是新用户，自动完成注册
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            // 写入数据库
            save(user);
        }
        // 返回user对象
        return user;
    }

    /**
     * 查询用户数
     * @param beginTime
     * @param endTime
     * @return
     */
    @Override
    public Integer getUserCount(LocalDateTime beginTime, LocalDateTime endTime) {
        return lambdaQuery()
                .gt(beginTime!=null,User::getCreateTime, beginTime)
                .lt(endTime!=null,User::getCreateTime, endTime)
                .count();
    }

    /**
     * 调用微信接口服务，获得用户的openId
     *
     * @param userLoginDTO
     * @return
     */
    private String getOpenid(UserLoginDTO userLoginDTO) {

        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("appid", weChatProperties.getAppid());
        paramMap.put("secret", weChatProperties.getSecret());
        paramMap.put("js_code", userLoginDTO.getCode());
        paramMap.put("grant_type", "authorization_code");
        String json = HttpClientUtil.doGet(VX_LOGIN, paramMap);

        // 解析json，并获取openid的值
        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");
        return openid;
    }
}
